package com.vencent.spring.web;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.vencent.spring.dao.SpittlerRepository;
import com.vencent.spring.model.Spittler;

@Controller
@RequestMapping("/spitter")
public class SpittlerController {
	
	private SpittlerRepository rep;
	
	@Autowired
	public SpittlerController(SpittlerRepository rep) {
		super();
		this.rep = rep;
	}

	@RequestMapping(value = "/register", method = RequestMethod.GET)
	public String showRegistrationForm(Model model){
		Spittler spittler = new Spittler();
		spittler.setFirstName("Jack");
		spittler.setLastName("Lee");
		model.addAttribute(spittler);
		return "registerForm";
	}
	
	/**
	 * forward : local.url don't change, the server will carry the things into request to visit other's Resource in the server.
	 * redirect : local.url will be change, the server will add sometings into Response to tell the Client to visit the other's Resources in the server.
	 * forward efficiency can be higher than redirect , you can use forward when you login, And you can use redirect when you logout.
	 * @param spitter
	 * @return
	 */
	@RequestMapping(value = "/register", method = RequestMethod.POST)
	public String processRegistration(@Valid Spittler spitter, Errors errors){
		if(errors.hasErrors()){
			return "registerForm";
		}
		rep.save(spitter);
		return "redirect:/spitter/" + spitter.getUserName();
	}
	
	@RequestMapping(value = "/show/{userName}", method = RequestMethod.GET)
	public String show(@PathVariable String userName, Model model){
		model.addAttribute(rep.queryByName(userName));
		return "profile";
	}
	
	@RequestMapping(value = "/registerThymeleaf", method = RequestMethod.GET)
	public String showRegistrationFormThymeleaf(Model model){
		Spittler spittler = new Spittler();
		spittler.setFirstName("Jacky");
		spittler.setLastName("Lee");
		model.addAttribute(spittler);
		return "/templates/registerFormThymeleaf";
	}
	
	/**
	 * @param spitter
	 * @return
	 */
	@RequestMapping(value = "/registerThymeleaf", method = RequestMethod.POST)
	public String processRegistrationThymeleaf(@Valid Spittler spitter, Errors errors){
		if(errors.hasErrors()){
			return "/templates/registerFormThymeleaf";
		}
		rep.save(spitter);
		return "redirect:/spitter/" + spitter.getUserName();
	}
}
